﻿using Abp;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using AutoMapper.QueryableExtensions;
using FwProject.Com.Dto;
using FwProject.ShopApplication;
using FwProject.ShoppingMall.Com;
using FwProject.ShoppingMall.Shop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;

namespace FwProject.Com
{
    public class ContentManageAppService : FwProjectAppServiceBase, IContentManageAppService
    {
        private readonly IRepository<ContentManage, Guid> _contentManageRepository;
        private readonly IRepository<ShopProduct, Guid> _shopProductRepository;
        public IGuidGenerator _guid { get; set; }

        public ContentManageAppService(IRepository<ContentManage, Guid> contentManageRepository, IRepository<ShopProduct, Guid> shopProductRepository)
        {
            _contentManageRepository = contentManageRepository;
            _shopProductRepository = shopProductRepository;
            _guid = SequentialGuidGenerator.Instance;
        }

        public async Task<LayerDataBaseDto> GetLayerDataAsync(int page, int limit, string keyword)
        {
            var query = _contentManageRepository.GetAllIncluding(o => o.ContentType);
            if (!string.IsNullOrEmpty(keyword))
                query = query.Where(o => o.Title.Contains(keyword));

            var pagelist = await query.OrderByDescending(o => o.CreationTime).ProjectTo<ContentManageOutputDto>().ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }

        public async Task<ContentManageOutputDto> GetEntityByIdAsync(Guid id)
        {
            var entity = await _contentManageRepository.GetAsync(id);
            var data = entity.MapTo<ContentManageOutputDto>();
            if (data.AccessType== AccessType.Details&&!string.IsNullOrEmpty(data.Data))
            {
                data.ShopProductName =  _shopProductRepository.GetAll().Where(o=>o.Id==new Guid(data.Data)).FirstOrDefault()?.ProductName;
            }
            return data;
        }
        public async Task<Guid> CreateAsync(ContentManageEnterDto input)
        {
            var entity = input.MapTo<ContentManage>();
            entity.Id = _guid.Create();
            return await _contentManageRepository.InsertAndGetIdAsync(entity);
        }

        public async Task ModifyAsync(Guid id, ContentManageEnterDto input)
        {
            var entity = await _contentManageRepository.GetAsync(id);
            input.MapTo(entity);
            await _contentManageRepository.UpdateAsync(entity);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _contentManageRepository.DeleteAsync(id);
        }

    }
}
